<?php

namespace catchAdmin\phone\controller;

use catcher\base\CatchController;
use catcher\exceptions\FailedException;
use catcher\exceptions\MobileLoginErrorException;
use thans\jwt\facade\JWTAuth;

class LoginCatchController extends CatchController
{

    private $jwt = null;

    private $no_login_url = [
        'NewsClass/index',
        'News/index',
        'News/read',
        'News/indexBanner',
        'Need/indexPub',
        'Need/read',
    ];


    public function __construct()
    {
        try {
            $this->jwt = JWTAuth::auth();
        } catch (\Exception $e) {
            saveAccessLog('登陆验证失败1', 'Request checkLogin');

            if (in_array(request()->pathinfo(), $this->no_login_url)) {
                return;
            }

            throw new MobileLoginErrorException('登陆验证失败2');
        }

        if (empty($this->jwt['id'])) {
            if (in_array(request()->pathinfo(), $this->no_login_url)) {
                return;
            }

            throw new MobileLoginErrorException('登陆验证失败3');
        }

        $login_id = $this->jwt['id']->getValue();

//        $login_id = 13;

        $login_user_msg = (new \catchAdmin\model\WechatUser())
            ->where('id', $login_id)
            ->find();
        if (empty($login_user_msg)) {
            throw new MobileLoginErrorException('登陆验证失败4');
        }

        $login_user_msg->last_login_time = time();
        $login_user_msg->save();

        saveAccessLog($login_id, 'Request checkLogin login_id');

        session('login_id', $login_id);
    }


}
